<template>
  <div class="page">
    <h2>消耗量分析</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按药品名称/编码搜索" clearable style="flex:1" @clear="onClear" />
      <el-date-picker v-model="range" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" style="width:320px" />
      <el-select v-model="groupBy" placeholder="按...分组" style="width:160px">
        <el-option label="药品" value="drug" />
        <el-option label="科室" value="dept" />
      </el-select>
      <div style="display:flex;gap:8px">
        <el-button @click="exportCSV">导出CSV</el-button>
        <el-button type="primary" @click="refresh">刷新</el-button>
      </div>
    </div>

    <div class="muted">说明：消耗量分析用于统计一定时间范围内精神类药品的使用量与趋势，以便监管与配送。此页面为前端静态演示，真实系统应基于处方、发药与回收数据计算。</div>

    <div style="display:flex;gap:12px;margin-top:12px">
      <div class="stat-card">
        <div class="stat-title">总消耗量</div>
        <div class="stat-value">{{ totalConsumed }} 单位</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">最大消耗药品</div>
        <div class="stat-value">{{ topDrug.name }} ({{ topDrug.qty }} 单位)</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">活跃科室数</div>
        <div class="stat-value">{{ activeDepts }}</div>
      </div>
    </div>

    <el-table :data="grouped" stripe border style="width:100%;margin-top:12px">
      <el-table-column prop="key" :label="groupBy==='drug'? '药品' : '科室'" />
      <el-table-column prop="consumed" label="消耗量" width="140" />
      <el-table-column prop="count" label="处方数" width="120" />
      <el-table-column prop="avgPerPrescription" label="平均每处方" width="150" />
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <div style="flex:1"></div>
      <div class="muted">展示 {{ grouped.length }} 行汇总</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

const q = ref('');
const range = ref([]);
const groupBy = ref('drug');
const data = ref([]);

// 示例数据来源于公开的消耗分析做法：按药品/科室汇总处方与发药数量
const DEFAULT = [
  { drugCode:'S-001', drugName:'氟哌啶醇注射液', dept:'急诊', consumed:120, prescriptions:40 },
  { drugCode:'S-002', drugName:'劳拉西泮片', dept:'门诊', consumed:220, prescriptions:80 },
  { drugCode:'S-003', drugName:'奥氮平片', dept:'住院', consumed:90, prescriptions:30 },
  { drugCode:'S-002', drugName:'劳拉西泮片', dept:'住院', consumed:60, prescriptions:25 }
];

onMounted(()=>{ data.value = JSON.parse(JSON.stringify(DEFAULT)); });

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(r=>{
    if(qq && !(r.drugName.toLowerCase().includes(qq) || r.drugCode.toLowerCase().includes(qq) || r.dept.toLowerCase().includes(qq))) return false;
    // 时间筛选在演示数据中不生效
    return true;
  });
});

const grouped = computed(()=>{
  const map = new Map();
  filtered.value.forEach(r=>{
    const key = groupBy.value==='drug' ? `${r.drugCode}__${r.drugName}` : r.dept;
    if(!map.has(key)) map.set(key,{ key, consumed:0, count:0, prescriptions:0 });
    const it = map.get(key);
    it.consumed += r.consumed || 0;
    it.prescriptions += r.prescriptions || 0;
    it.count += 1;
  });
  const arr = Array.from(map.values()).map(x=>({ key: groupBy.value==='drug' ? x.key.split('__')[1] : x.key, consumed: x.consumed, count: x.prescriptions, avgPerPrescription: (x.consumed / (x.prescriptions||1)).toFixed(2) }));
  arr.sort((a,b)=>b.consumed - a.consumed);
  return arr;
});

const totalConsumed = computed(()=> filtered.value.reduce((s,r)=>s+(r.consumed||0),0) );
const topDrug = computed(()=>{
  const byDrug = {};
  filtered.value.forEach(r=>{ byDrug[r.drugName] = (byDrug[r.drugName]||0) + (r.consumed||0); });
  const entries = Object.entries(byDrug);
  if(entries.length===0) return { name:'-', qty:0 };
  entries.sort((a,b)=>b[1]-a[1]); return { name: entries[0][0], qty: entries[0][1] };
});
const activeDepts = computed(()=> new Set(filtered.value.map(r=>r.dept)).size );

function exportCSV(){ const rows = [['key','consumed','count','avgPerPrescription'], ...grouped.value.map(r=>[r.key,r.consumed,r.count,r.avgPerPrescription])]; const txt = rows.map(r=>r.map(c=>`"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([txt],{type:'text/csv'}); const url = URL.createObjectURL(blob); const a=document.createElement('a'); a.href=url; a.download='consumption_analysis.csv'; a.click(); URL.revokeObjectURL(url); }
function refresh(){ ElMessage.success('已刷新（演示）'); }
function onClear(){}
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
.stat-card{background:#fff;border:1px solid #e6e6e6;padding:12px;border-radius:6px;min-width:200px}
.stat-title{color:#888;font-size:13px}
.stat-value{font-size:18px;margin-top:6px}
</style>